<template>
    <div class="content">
        <el-row>
            <el-col :span="12">
                <RiskTableP
                    :ref="'risk-table'"
                    :tableConfig="tableConfig"
                    :tableData="tableData"
                    :column="tableColumns"
                    v-loading="tableLoading"
                    style="height: 40vh"
                >
                </RiskTableP>
                <div class="line-chart">
                    <!-- 折线图 -->
                    <div ref="chartDom" class="com-chart"></div>
                    <div class="com-table" v-if="tableData.length > 0">
                        <table>
                            <thead>
                                <tr>
                                    <th></th>
                                    <th v-for="item in tableData" :key="item.recordId">
                                        {{ item.tradeDate }}
                                    </th>
                                </tr>
                            </thead>
                            <tbody>
                                <tr>
                                    <td>阈值</td>
                                    <td v-for="(item, index) in tableData" :key="index">{{ mul100(item.thresholdValue) }}</td>
                                </tr>
                                <tr>
                                    <td>实际值</td>
                                    <td v-for="(item, index) in tableData" :key="index">{{ mul100(item.result) }}</td>
                                </tr>
                            </tbody>
                        </table>
                    </div>
                </div>
            </el-col>
            <el-col :span="12">
                <OverReasonDetail
                    :transToResultDetail="curDateDetail || transToResultDetail"
                    :showDateSearch="true"
                    :isActive="$attrs.isActive"
                ></OverReasonDetail>
            </el-col>
        </el-row>
    </div>
</template>
<script lang="ts">
import RiskTableP from '@/common/components/risk-table-plus.vue';
import { ColumnVO, TableConfigVO } from '@/common/vo';
import { Component, Prop, Vue, Watch } from 'vue-property-decorator';
import API from '../api/over-reason-follow';
import OverReasonDetail from './over-reason-detail.vue';
import * as echarts from 'echarts';
import { accMul } from '@/utils/tools';
import DictionConstUtil from '@/utils/diction-const-util';

@Component({ name: 'OverFollowDetail', components: { RiskTableP, OverReasonDetail } })
export default class OverFollowDetail extends Vue {
    // 详情数据
    @Prop() transToResultDetail;
    curDateDetail: any = null; // 当前点击日期
    tableKey: number = -1;
    tableConfig: TableConfigVO = {
        rowKey: 'recordId',
    };
    tableLoading: boolean = false;
    tableData: any[] = [];
    tableColumns: ColumnVO[] = [
        {
            field: 'tradeDate',
            title: '日期',
            width: 100,
        },
        {
            field: 'entryCode',
            title: '条目编号',
            width: 100,
        },
        {
            field: 'entryName',
            title: '风险说明',
            minWidth: 140,
        },

        {
            field: 'thresholdValue',
            title: '阈值',
            width: 100,
            render: value => this.mul100(value),
        },
        {
            field: 'result',
            title: '计算结果',
            width: 100,
            render: value => this.mul100(value),
        },
        {
            field: 'numerator',
            title: '分子值',
            minWidth: 100,
        },
        {
            field: 'denominator',
            title: '分母值',
            minWidth: 100,
        },
        {
            field: 'triggerType',
            title: '触警类型',
            render: value => DictionConstUtil.ThresholdType[value],
            minWidth: 100,
        },
    ];

    getOverRecordList() {
        this.tableLoading = true;
        let { serialNo, branchNo, entryKey, entryKey2, firstOverrunDate, firstRestoreDate } = this.transToResultDetail;
        return new Promise((resolve, reject) => {
            API.overFollowRecordList({
                serialNo,
                branchNo,
                entryKey,
                entryKey2,
                firstOverrunDate,
                firstRestoreDate,
                curData: this.transToResultDetail,
                // paging:this.paging,// 是否添加分页
            } as any)
                .then((res: any) => {
                    this.tableData = res;
                    let failed = [];
                    let succeed = [];
                    let tags = [];
                    this.tableData.map(item => {
                        failed.push(item.thresholdValue);
                        succeed.push(item.result);
                        tags.push(item.tradeDate);
                    });
                    this.data = { failed, succeed, tags };
                    this.tableLoading = false;
                    resolve(res);
                })
                .catch(err => {
                    this.tableLoading = false;
                    reject(err);
                })
                .finally(() => {
                    // let res = [
                    //     {
                    //         calcTimes: 0,
                    //         entryCode: '1553',
                    //         entryKey: '47:1553:6:469:5688-47:1553:12:0:0',
                    //         entryKey2: '1553:469:5688',
                    //         entryName: '控转回质押导致的被动超标',
                    //         prohibitionDate: 1,
                    //         result: 1.52380952,
                    //         resultId: 1531003018,
                    //         thresholdLevel: '2',
                    //         thresholdValue: 0.5,
                    //         tradeDate: 20230818,
                    //         triggerDay: 1,
                    //         triggerType: '3',
                    //     },
                    //     {
                    //         calcTimes: 0,
                    //         entryCode: '1553',
                    //         entryKey: '47:1553:6:469:5688-47:1553:12:0:0',
                    //         entryKey2: '1553:469:5688',
                    //         entryName: '控转回质押导致的被动超标',
                    //         prohibitionDate: 1,
                    //         result: 1.52380952,
                    //         resultId: 1531003019,
                    //         thresholdLevel: '2',
                    //         thresholdValue: 0.5,
                    //         tradeDate: 20230819,
                    //         triggerDay: 1,
                    //         triggerType: '3',
                    //     },
                    //     {
                    //         calcTimes: 0,
                    //         entryCode: '1553',
                    //         entryKey: '47:1553:6:469:5688-47:1553:12:0:0',
                    //         entryKey2: '1553:469:5688',
                    //         entryName: '控转回质押导致的被动超标',
                    //         prohibitionDate: 1,
                    //         result: 1.52380952,
                    //         resultId: 1531003016,
                    //         thresholdLevel: '2',
                    //         thresholdValue: 0.5,
                    //         tradeDate: 20230820,
                    //         triggerDay: 1,
                    //         triggerType: '3',
                    //     },
                    //     {
                    //         calcTimes: 0,
                    //         entryCode: '1553',
                    //         entryKey: '47:1553:6:469:5688-47:1553:12:0:0',
                    //         entryKey2: '1553:469:5688',
                    //         entryName: '控转回质押导致的被动超标3',
                    //         prohibitionDate: 1,
                    //         result: 1.52380952,
                    //         resultId: 1531003018,
                    //         thresholdLevel: '2',
                    //         thresholdValue: 0.5,
                    //         tradeDate: 20230821,
                    //         triggerDay: 1,
                    //         triggerType: '3',
                    //     },
                    // ];
                    // this.tableData = res;
                    // let failed = [];
                    // let succeed = [];
                    // let tags = [];
                    // this.tableData.map(item => {
                    //     failed.push(item.thresholdValue);
                    //     succeed.push(item.result);
                    //     tags.push(item.tradeDate);
                    // });
                    // this.data = { failed, succeed, tags };
                    // this.tableLoading = false;
                });
        });
    }

    chartInstance: any = null;
    data: any = {
        failed: [],
        succeed: [],
        tags: [],
    };

    @Watch('data', { immediate: true, deep: true })
    onWatchData(newData) {
        if (newData) {
            let that = this;
            this.$nextTick(() => {
                that.updateChart();
            });
        }
    }

    mounted() {
        this.$watch(
            () => {
                return this.$attrs.isActive;
            },
            val => {
                console.log(val, 'val_______');

                if (val) {
                    this.updateChart();
                }
            }
        );
        this.getOverRecordList();
        // window.handleClick = this.handleClick;
        this.initChart();
        this.updateChart();
        window.addEventListener('resize', this.updateChart);
    }

    initChart() {
        let that = this;
        console.log(this.$refs.chartDom, 'this.$refs.chartDom');

        this.chartInstance = echarts.init(this.$refs.chartDom);
        let initOption = {
            title: {
                show: true,
                text: `{b|${that.transToResultDetail.entryName} (${that.transToResultDetail.fundName})}`,
                left: 'center',
                textStyle: {
                    color: 'black',

                    fontWeight: 'bold',
                    rich: {
                        b: {
                            fontWeight: 'bold',
                            fontSize: 15,
                            padding: [0, 0, 0, 5],
                        },
                    },
                },
            },
            tooltip: {
                show: false,
            },
            legend: {
                trigger: 'item',
                icon: 'rect',
                selectedMode: false,
                left: '40%',
                bottom: '0',
                itemHeight: 3,
                itemWidth: 15,
                textStyle: {
                    color: '#9aa8ba',
                    fontSize: 12,
                },
            },
            grid: {
                left: '3%',
                right: '3%',
                width: '92%', // 宽度
                bottom: '20px',
                top: '35px',
                containLabel: true,
            },

            xAxis: {
                type: 'category',
                boundaryGap: false,
                // min: 20,
                nameTextStyle: {
                    color: '#aaaaaa',
                },
                axisTick: {
                    // inside: true,
                    show: false,
                },
                axisLine: {
                    lineStyle: {
                        color: 'gray',
                        width: 1,
                    },
                },
                axisLabel: {
                    fontSize: 10,
                    textStyle: {
                        color: '#333',
                    },
                    margin: 20,
                },
                data: this.data['tags'],
            },
            yAxis: {
                type: 'value',
                scale: true,
                boundaryGap: false,
                // min: 20,
                // max: 'dataMax',
                // splitNumber: 4,
                // min: () => {
                //     // 获取y轴的刻度区间大小
                //     console.log(this.chartInstance.getModel().getComponent('yAxis').axis.scale._interval);
                //     let interval = this.chartInstance.getModel().getComponent('yAxis').axis.scale._interval;
                //     return interval;
                // },
                axisTick: {
                    show: false,
                },
                axisLine: {
                    show: false,
                    lineStyle: {
                        color: 'gray',
                        width: 1,
                    },
                },

                axisLabel: {
                    show: true,
                    showMinLabel: true, // 不显示最小刻度
                    fontSize: 10,
                    textStyle: {
                        color: '#333',
                    },
                    margin: 20,
                    formatter: value => {
                        return accMul(value, 100) + '%';
                    },
                },
                splitLine: {
                    // 网格分割线
                    show: true,
                    lineStyle: {
                        color: '#dedede',
                        type: 'solid',
                    },
                },
            },
            series: [
                {
                    // stack: '实际值',
                    name: '阈值',
                    type: 'line',
                    symbol: 'circle',
                    // symbol: 'none', // 去除小圆点
                    smooth: true, // 曲线
                    // showSymbol: false,
                    symbolSize: 3,

                    label: {
                        show: true,
                        position: 'top',
                        fontSize: 10,
                        formatter: ele => {
                            return this.mul100(ele.data);
                        },
                    },

                    labelLayout: function (params) {
                        var random = Math.random() * 100;
                        return {
                            x: params.dataIndex * 100 - random,
                        };
                    },
                    // stack: true,
                    data: this.data['succeed'],
                    // data: [33, 28, 22, 28, 35, 40, 35, 26, 30, 28, 28, 36],
                },
                {
                    name: '实际值',
                    type: 'line',
                    symbol: 'circle',
                    // symbol: 'none', // 去除小圆点
                    emphasis: {
                        focus: 'series',
                    },
                    symbolSize: 3,
                    label: {
                        show: true,
                        position: 'bottom',
                        fontSize: 10,
                        formatter: ele => {
                            return this.mul100(ele.data);
                        },
                    },
                    smooth: true,
                    data: this.data['failed'],
                    // data: [21, 25, 30, 36, 43, 46, 41, 30, 15, 7, 7, 30],
                    labelLayout: function (params) {
                        var random = Math.random() * 100;
                        return {
                            x: params.dataIndex * 100 - random,
                        };
                    },
                },
            ],
            color: ['#ed7d31', '#9dc3e6'],
        };
        this.chartInstance.setOption(initOption);
        // 点击事件
        this.chartInstance.on('click', param => {
            console.log(param, 'param');
            // 用到的是横坐标param.name日期值
            // this.handleClick(param.name);
            this.curDateDetail = {
                startDate: param.name,
                endDate: param.name,
                firstOverrunDate: this.transToResultDetail.firstOverrunDate,
                firstRestoreDate: this.transToResultDetail.firstRestoreDate,
                entryKey: this.transToResultDetail.entryKey,
                entryKey2: this.transToResultDetail.entryKey2,
                entryName: this.transToResultDetail.entryName,
            };
        });
    }

    updateChart() {
        setTimeout(() => {
            const titleFontSize = ((this.$refs.chartDom as any).offsetWidth / 100) * 5.6;
            const dataOption = {
                axisLabel: {
                    textStyle: {
                        fontSize: titleFontSize,
                    },
                },
                xAxis: { data: this.data['tags'] },
                series: [{ data: this.data['succeed'] }, { data: this.data['failed'] }],
            };
            this.chartInstance.setOption(dataOption);
            this.chartInstance.resize();
        }, 200);
    }

    // handleClick(name: string) {
    // this.handleXlabel(name);
    // // console.log(this.dateTime);
    // this.detailShow = true;
    // this.currentData = {
    //     seriesName: seriesName == '阈值' ? '成功' : '失败',
    //     data: data,
    //     time: name,
    //     seriesIndex: seriesIndex == 0 ? 1 : 0, // 注意:页面对应0是成功;但是实际1才是成功
    // };
    // console.log(this.dateTimeData, name, 'name-------');
    // }
    /**
     * 获取完整当前横轴点对应的时间
     */
    handleXlabel(name) {
        // let dataTime = '';
        // let xlabel = '';
        // if (this.unit == 'hour') {
        //     xlabel = name.substr(0, 2);
        //     dataTime = this.lineParams.beginDate + xlabel;
        // } else if (this.unit == 'day') {
        //     xlabel = name.replace(/\//g, '');
        //     dataTime = this.lineParams.beginDate.substr(0, 4) + xlabel;
        //     // dataTime = this.dateTimeData.find((ele: any) => ele.indexOf(xlabel) !== -1);
        // } else if (this.unit == 'month') {
        //     xlabel = name.replace(/\//g, '');
        //     dataTime = xlabel;
        // }
        // this.dataTime = dataTime;
    }

    dispose() {
        this.chartInstance.dispose(); // 销毁实例
        this.initChart();
    }

    beforeDestroy() {
        this.chartInstance.clear();
        this.chartInstance.dispose();
        this.chartInstance = null;
    }

    mul100(value) {
        return accMul(value, 100) + '%';
    }
}
</script>
<style lang="scss" scoped>
.content {
    height: calc(100vh - 47px);
    .el-row {
        .el-col:first-child {
            padding: 10px;
        }
        .line-chart {
            height: calc(60vh - 70px);
            width: 100%;
            .com-chart {
                width: 100%;
                height: calc(100% - 130px);
                overflow: hidden;
            }

            .com-table {
                height: 130px;
            }
            table {
                width: 100%;
                height: 100%;
                border: 1px solid #ccc;

                /* 固定表头 */
                thead,
                tbody tr {
                    display: table;
                    width: 100%;
                    table-layout: fixed;
                    border-spacing: 0px !important;
                    height: 40px;
                }
                thead tr th,
                tbody tr td {
                    border: 1px solid #ccc;
                    border-top: none;
                    border-left: none;
                    color: #333;
                    &:last-child {
                        border-right: none;
                    }
                }

                /* 控制表格滑动 */
                tbody {
                    display: block;
                    height: calc(100% - 25px);
                    // overflow-y: scroll;
                }

                /* 隐藏  y轴的滚动条，仍然可以上下滚动 */
                // tbody::-webkit-scrollbar {
                //     display: none;
                // }

                td {
                    text-align: center;
                    overflow: hidden;
                    text-overflow: ellipsis;
                    white-space: nowrap;
                    font-size: 13px;
                }
            }
        }
    }
    .search-content {
        & > span {
            margin: 0 10px;
            color: #333;
        }
        .el-button {
            margin-left: 10px;
        }
    }
    .chart-content {
        margin: 10px 0;
        height: 300px;
        h3 {
            color: #333;
        }
    }
    .table-content {
        height: calc(100vh - 420px);
    }
}
</style>
